package com.example.mygame;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

import java.util.Vector;

public class PlayGround extends SurfaceView {

    private static final int ROW = 3;//行 对应y
    private static final int COL = 3;//列 对应x
    //暂时不用
    private static final int BLOCKS = 0;//路障数

    private ChessPiece[][] matrix;
    private int King_A[] = {0, 0};
    private int King_B[] = {2, 2};

    public PlayGround(Context context) {
        super(context);
        getHolder().addCallback(callback);

        matrix = new ChessPiece[ROW][COL];
        for (int i = 0; i < ROW; i++) {
            for (int j = 0; j < COL; j++) {
                matrix[i][j] = new ChessPiece(j, i);
            }
        }
        //Log.d("TAG", "matrix created");
        System.out.println("matrix created");

        initGame();
    }

    private ChessPiece getChessPiece(int x, int y) {
        return matrix[y][x];//x,y->row,col
    }

    private void redraw() {
        Canvas c = getHolder().lockCanvas();
        c.drawColor(Color.CYAN);
        getHolder().unlockCanvasAndPost(c);
        System.out.println("Background color changed");
    }


    Callback callback = new Callback() {

        @Override
        public void surfaceCreated(@NonNull SurfaceHolder holder) {
            redraw();
        }

        @Override
        public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
        }

        @Override
        public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        }
    };

    private void initGame() {
//        for (int i = 0; i < ROW; i++) {
//            for (int j = 0; j < COL; j++) {
//                matrix[i][j].setCamp(ChessPiece.CAMP_WHITE);
//            }
//        }
        getChessPiece(King_A[0], King_A[1]).setCamp(ChessPiece.CAMP_RED);
        getChessPiece(King_B[0], King_B[1]).setCamp(ChessPiece.CAMP_BLUE);
        for (int i = 0; i < BLOCKS; ) {
            int x = (int) ((Math.random() * 1000) % COL);
            int y = (int) ((Math.random() * 1000) % ROW);

            if (getChessPiece(x, y).getCamp() == ChessPiece.CAMP_WHITE) {
                getChessPiece(x, y).setCamp(ChessPiece.CAMP_BLOCK);
                i++;
                //Log.d("TAG","Block: " + i + " created");
                System.out.println("Block: " + i + " created");
            }
        }
        //Log.d("TAG","Initialization complete");
        System.out.println("Initialization complete");
    }
}